package org.toolbook.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.toolbook.interceptor.LoginInterceptor;
import org.toolbook.model.User;
import org.toolbook.util.PropUtil;
import org.toolbook.util.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
/**
 * ajaxFileUpload的后台，完成异步上传缩览图
 * @author meigang
 * @date 2015-06-23 22:35
 *
 */
//@WebServlet("/ulp.servlet")
@Before(LoginInterceptor.class)
public class UploadLookPhotoServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//需要返回的fileName  
        String uuidFileName = null;  
        String lookPhotoType = null; 
        //参考资料  http://commons.apache.org/proper/commons-fileupload/using.html  
        // Check that we have a file upload request  
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);  
          
        // Create a factory for disk-based file items  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
  
        // Configure a repository (to ensure a secure temp location is used)  
        ServletContext servletContext = this.getServletConfig().getServletContext();  
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");  
        factory.setRepository(repository);  
  
        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory);  
  
        // Parse the request  
        String tempPath = null;
        Map<String, String> map = new HashMap<String, String>();
        try {  
            List<FileItem> items = upload.parseRequest(req);  
            for(FileItem item : items) {  
                //其他参数  
                String type = item.getContentType();  
                if(type == null) {  
                  //System.out.println(item.getString(item.getFieldName())); 
                	String field = item.getFieldName();
                	if(field.equals("lookPhotoType")){
                		lookPhotoType = item.getString();
                	}
                    continue;  
                }  
                boolean b = false;
                //文件参数  
                String fileName = item.getName(); 
                String ext = org.springframework.util.StringUtils.getFilenameExtension(fileName);
                if(ext == null){
                	map.put("flag", "1");
                	resp.getWriter().print(JsonKit.mapToJson(map, 8));
                	resp.getWriter().flush();
                	return;
                }
                //做文件验证
                if(!(ext.equals("jpg") || ext.equals("png") || ext.equals("gif"))){
                	//文件类型不支持
                	map.put("flag", "2");
                	b = true;
                }
                //文件大小
                if(item.getSize() > 2 * 1024 * 1024){
                	map.put("flag", "3");
                	b = true;
                }
                if(b){
                	resp.getWriter().print(JsonKit.mapToJson(map, 8)); 
                	resp.getWriter().flush();
                	return;
                }
                
                //设置保存文件路径  
                User u = (User) req.getSession().getAttribute(PropUtil.getProperty("SESSION_LOGIN_KEY"));
                tempPath = "/upload/" + lookPhotoType +"/" + u.get("id") + "/" + 
                		StringUtils.getDateString(new Date(), "yyyyMMdd");
                
                String realPath = PathKit.getWebRootPath() + tempPath;
                File dir = new File(realPath);  
                if(!dir.exists()){
                	dir.mkdirs();
                }
                //uuid文件名
                uuidFileName = UUID.randomUUID() +"."+ org.springframework.util.StringUtils.getFilenameExtension(fileName);
                File f = new File(realPath + "/" + uuidFileName);  
                //保存  
                item.write(f);
            }  
        } catch (FileUploadException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
          
        //返回结果  
        map.put("flag", "0");
        map.put("filepath", tempPath +"/"+uuidFileName);
        resp.getWriter().print(JsonKit.mapToJson(map, 8));  
        resp.getWriter().flush();
    } 
	
}
